/**
 * 
 */
package org.wolf.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * @author 何小锋
 * 
 */
public class XMLUtil {

	/**
	 * 对象输出为XML
	 * 
	 * @param target
	 * @param file
	 * @throws JAXBException
	 */
	public static void marshall(Object target, File file) throws JAXBException {
		if (target == null || file == null)
			return;
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(file);
			marshall(target, out);
		} catch (FileNotFoundException e) {
			throw new JAXBException(e.getMessage(), e);
		} finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
				}
			}
		}
	}

	/**
	 * 对象输出为XML
	 * 
	 * @param target
	 * @param out
	 * @throws JAXBException
	 */
	public static void marshall(Object target, OutputStream out)
			throws JAXBException {
		if (target == null || out == null)
			return;
		JAXBContext context = JAXBContext.newInstance(target.getClass());
		// 下面代码演示将对象转变为xml
		Marshaller m = context.createMarshaller();
		m.marshal(target, out);
	}

	/**
	 * XML转换成对象
	 * 
	 * @param <T>
	 * @param clazz
	 * @param file
	 * @return
	 * @throws JAXBException
	 */
	public static <T> T unmarshall(Class<T> clazz, File file)
			throws JAXBException {
		if (file == null || clazz == null)
			return null;
		FileInputStream in = null;
		try {
			in = new FileInputStream(file);
			return unmarshall(clazz, in);
		} catch (FileNotFoundException e) {
			throw new JAXBException(e.getMessage(), e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
				}
			}
		}
	}

	/**
	 * XML转换成对象
	 * 
	 * @param <T>
	 * @param clazz
	 * @param in
	 * @return
	 * @throws JAXBException
	 */
	@SuppressWarnings("unchecked")
	public static <T> T unmarshall(Class<T> clazz, InputStream in)
			throws JAXBException {
		if (in == null || clazz == null)
			return null;
		JAXBContext context = JAXBContext.newInstance(clazz);
		Unmarshaller um = context.createUnmarshaller();
		return (T) um.unmarshal(in);
	}

}
